// Package dao
// @Time : 2025/11/4 10:50
// @Author : csg
// @Description:
package dao

import (
	"context"
	"cron_table_admin/internal/model"
	"errors"

	"gorm.io/gorm"
)

type UserDao struct {
	Db *gorm.DB
}

func NewUserDao(db *gorm.DB) *UserDao {
	return &UserDao{Db: db}
}

func (d *UserDao) GetDetailById(ctx context.Context, uid int64) (*model.User, error) {
	userCurd := &DbCrud[model.User]{
		Db: d.Db,
		Conditions: []map[string]any{
			{"id": uid},
		},
	}
	dataList, err := userCurd.DBRead(ctx)

	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, nil
		}
		return nil, err
	}
	return dataList[0], nil
}

func (d *UserDao) Update(ctx context.Context, updateData map[string]any, conditions []map[string]any) (int64, error) {
	userCurd := &DbCrud[model.User]{
		Db:         d.Db,
		DataMap:    updateData,
		Conditions: conditions,
	}
	affectRows, err := userCurd.DBUpdate(ctx)
	if err != nil {
		return 0, err
	}
	return affectRows, nil
}

func (d *UserDao) Create(ctx context.Context, user *model.User) (err error) {
	cronCurd := &DbCrud[model.User]{
		Db:       d.Db,
		DataList: []*model.User{user},
	}
	_, err = cronCurd.DBCreate(ctx)
	if err != nil {
		return err
	}
	return nil
}
